<template>
  <div class="login">
    <el-form
      ref="myForm"
      :model="form"
      class="myform"
      :rules="rules"
    >
      <h3>iHRM 后台登录系统</h3>
      <el-form-item prop="mobile">
        <el-input
          v-model="form.mobile"
          prefix-icon="el-icon-user-solid"
          placeholder="请输入手机号"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="form.password"
          prefix-icon="el-icon-lock"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      <el-button
        type="primary"
        class="but"
        :loading="loading"
        @click="submit"
      >
        登录
      </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import {loginApi} from '@/api/user.js'
import { mapActions } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      form: {
        mobile: '13800000002',
        password: '123456'
      },
      loading: false,
      // 定义校验规则
      rules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            // 定义手机号的规则
            const res = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
            // 测试数据
            const bool = res.test(value)
            bool ? callback() : callback(new Error('手机号不合法'))
          }, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapActions({
      userLogin: 'user/login'
    }),

    // 提交的点击事件
    submit() {
      // 全局验证表单
      this.$refs.myForm.validate(async result => {
        if (result) {
          try {
            this.loading = true
            console.log(this.form)
            await this.userLogin(this.form)
            this.loading = false
            this.$message({
              type: 'success',
              message: '登录成功'
            })
            this.$router.push('/')
            // 跳转之后是不是之前的页面
            const _redirect = this.query._redirect
            console.log(_redirect)
            if (_redirect) {
              // 跳转到主页跳转之前的页面
              this.$router.push(_redirect)
            }
          } catch (error) {
          }
        } else {
        }
      })
    }
  }
}
</script>

<style lang="scss">
.login {
  background-image: url('../../assets/common/login.jpg');
  height: 100%;
  .myform{
   width: 520px;
   height: 430px;
   margin: 0 auto;
   text-align: center;
   position: fixed;
   top: 50%;
   left: 50%;
   transform: translate(-50%,-50%);
   h3 {
     font-size: 45px;
     letter-spacing: 11px;
     color: #fff;
     font-weight: 400;
   }
   input {
     height: 50px;
   }
    .but {
   width: 100%;
   height: 55px;
 }
 i.el-icon-loading {
    font-size: 20px;
}
  }

}
</style>
